package com.snake.excel2java.excel.generator.file;

import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedList;
import java.util.List;

import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@NoArgsConstructor
public class GlobalCreator {

	
	public void generate() {
		
		File dir = new File("");

		String path = dir.getAbsoluteFile().getParentFile() + "/excel2java/";
		
		String excelDirPath = dir.getAbsoluteFile().getParentFile() + "/excels/";
		File exceldir = new File(excelDirPath);
		
		if(!exceldir.isDirectory())
			exceldir.mkdirs();
		
		log.info("generate java file from dir: {}", excelDirPath);
		
		String globalPath = excelDirPath + "\\global.xlsx";
		
		File globalFile = new File(globalPath);
		
		if(!globalFile.exists()) {
			
			log.info("file {} not exist....", globalPath);
			return;
		}
		
		String globalJavaPath = path + "\\src\\main\\java\\com\\snake\\excel2java\\excel\\global\\";
		
		File globalJavaDir = new File(globalJavaPath);
		
		if(!globalJavaDir.isDirectory())
			globalJavaDir.mkdirs();
		
		generateFile(globalFile, 2, globalJavaDir);
		

	}
	
	public void generateFile(File file, int startLine, File globalJavaDir) {
		
		List<String[]> context = readExcel(file, startLine);
		
		StringBuilder builder = new StringBuilder();
		
		builder.append("package com.snake.excel2java.excel.global;\r\n\r\n")
				.append("import lombok.Getter;\r\n")
				.append("import lombok.Setter;\r\n")
				.append("import lombok.ToString;\r\n\r\n")
				.append("@Getter\r\n")
				.append("@Setter\r\n")
				.append("@ToString\r\n")
			   .append("public abstract class GlobalData {\r\n\r\n");
		
//		StringBuilder getsetBuilder = new StringBuilder();
		
		StringBuilder nameBuilder = new StringBuilder();
		nameBuilder.append("\tpublic static final String[] NAMES = {");

		boolean isFirst = true;
		for(String[] values: context) {

			if(isFirst) {
				isFirst = false;
			} else {
				nameBuilder.append(",");
			}

			nameBuilder.append("\r\n\t\t");
			nameBuilder.append("\"")
					   .append(values[0])
					   .append("\"");

			
			String type = values[1];
			
			if(type.startsWith("string"))
				type = type.substring(0, 1).toUpperCase() + type.substring(1);
			
			builder.append("\tprotected ")
				   .append(type)
				   .append(" ")
				   .append(values[0])
				   .append(";\t\t// ")
				   .append(values[2])
				   .append("\r\n");	

			
		}
		
		nameBuilder.append("};\r\n\r\n");
		
		builder.append("\r\n\r\n\r\n")
		   .append(nameBuilder)
		   .append("\r\n\r\n");

		builder.append("\r\n\r\n}");
		
		File javaFile = new File(globalJavaDir + "\\GlobalData.java");
		
		try {
			FileOutputStream fout = new FileOutputStream(javaFile);
			
			fout.write(builder.toString().getBytes("UTF-8"));
			fout.close();
			
			log.info("\r\n\r\n--------------------- write file {} success ---------------------", javaFile.getAbsolutePath());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
			log.error("--------------------- write file error: {} ---------------------", e.getMessage());

			e.printStackTrace();
		}
		
	}
	
	public List<String[]> readExcel(File file, int startLine) {
		
		log.info("\r\n\r\n\r\n------------- read {} --------------\r\n", file.getName());
		
		XSSFWorkbook workbook2007 = null;
		
		List<String[]> result = null;
		int i = startLine;
		try {
			
			workbook2007 = new XSSFWorkbook(file);
			XSSFSheet sheet = workbook2007.getSheetAt(0);
			
//			FormulaEvaluator evaluator = sheet.getWorkbook()
//					  .getCreationHelper()
//					  .createFormulaEvaluator();  
//			evaluator.evaluateAll();
			
			int length = sheet.getLastRowNum() + 1;
			result = new LinkedList<>();
			
			for( ; i < length; ++i) {
				
				XSSFRow row = sheet.getRow(i);//类型

				if(null == row)
					continue;

				XSSFCell cell = row.getCell(0);
				if(null == cell)
					continue;

				String[] values = new String[3];
				values[0] = readString(row, 0);
				values[1] = readString(row, 2);
				values[2] = readString(row, 3);
				result.add(values);
				
				log.info("------------- reads row {}, {}, {}, {}", i, values[0], values[1], values[2]);
			}
			
			
			workbook2007.close();
			
		} catch (Exception e) {
			
			log.error("\r\n\r\n------------- read error in row {} --------------\r\n\r\n", i);
			log.error(e.toString());
			
			e.printStackTrace();
			
		} finally {
			
		}
		
		
		return result;
	}

	protected String readString(XSSFRow row, int index) {
		
		XSSFCell cell = row.getCell(index);
		
		return cell.getStringCellValue().trim();
	}

}
